package cn.imnaer.service.rpc.scenic.process;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;

import cn.imnaer.database.MatchConst;
import cn.imnaer.service.persistence.model.consts.FILTER;
import cn.imnaer.service.persistence.model.consts.SCENIC;
import cn.imnaer.service.rest.resquest.model.Filter;
import cn.imnaer.service.rpc.scenic.dao.ScenicDaoImpl;

public class ScenicSearchFilter2 {
	private ScenicDaoImpl scenicDao = ScenicDaoImpl.getInstance();

	private BSONObject order = new BasicBSONObject();
	private Filter filter;

	public ScenicSearchFilter2(Filter filter) {
		this.filter = filter;

	}

	public BSONObject getOrder() {
		if (filter.sortType != null || !filter.sortType.isEmpty()) {
			String type = filter.sortType;
			switch (type) {
			case FILTER.SORT_BY_SCORE:
				order.put(SCENIC.score, -1);
				break;
			case FILTER.SORT_BY_COLLECT:
				order.put(SCENIC.collectCount, -1);
				break;
			case FILTER.SORT_BY_DISTANCE:
				order.put(SCENIC.distance, -1);
				break;
			default:
				order = null;
				break;
			}
		}
		return this.order;

	}

	/**
	 * 县级市怎么办？
	 * 
	 * @param keyword
	 * @return
	 */
	public BSONObject getQuery(String keyword) {
		BasicBSONObject query = new BasicBSONObject();
		// 匹配国家
		if (keyword != null && !keyword.isEmpty() && keyword.length() >= 2&&keyword.length()<=5) {
			query.put(SCENIC.countryName, this.getMatcherBsonObejct(keyword));
			int count = this.getCount(query);
			if (count > 0) {
				return query;
			} else {
				// 匹配省份
				query.clear();
				query.put(SCENIC.stateName, this.getMatcherBsonObejct(keyword));
				count = this.getCount(query);
				if (count > 0) {
					return query;
				} else {
					// 匹配城市
					query.clear();
					query.put(SCENIC.cityName, this.getMatcherBsonObejct(keyword));
					count = this.getCount(query);
					if (count > 0) {
						return query;
					}else{
						query.clear();
						BSONObject matcher = new BasicBSONObject();
						matcher.put(MatchConst._REGEX, keyword);
						query.put(SCENIC.scenicName, matcher);
						return query;
					}

				}
			}
		} else {
			// 匹配景点
			query.clear();
			BSONObject matcher = new BasicBSONObject();
			matcher.put(MatchConst._REGEX, keyword);
			query.put(SCENIC.scenicName, matcher);
			return query;
		}

	}

	public int getCount(BasicBSONObject query) {
		return this.scenicDao.getCount(query);
	}

	/**
	 * 行首匹配。国家，省份与城市是必须大于两个字的。
	 * 
	 * @param keywords
	 * @return
	 */
	private BSONObject getMatcherBsonObejct(String keywords) {
		BSONObject matcher = new BasicBSONObject();
		matcher.put(MatchConst._REGEX, "^" + keywords + ".*");
		return matcher;

	}
}
